<template>
  <view class="container">
    <uni-forms
      ref="formRef"
      :model="formData">
      <uni-forms-item name="traceUrlUnicode">
        <div class="flex">
          <uni-easyinput prefixIcon="search" type="text" v-model="formData.traceUrlUnicode" placeholder="请输入追溯码登记号" />
          <text class="search" @click="handleSubmit">搜索</text>
        </div>
      </uni-forms-item>
    </uni-forms>
    
    <div class="ft">
      <button type="primary" @click="scanCode">扫一扫</button>
    </div>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { apis as APIS } from "@/api/yiqiyipin.js";
import { router } from "@/router/index.js";

const formData = ref({
  traceUrlUnicode: ''  //20241122204903834
});


const rules = ref({
  traceUrlUnicode: {
    rules: [{ required: true, errorMessage: "请输入追溯码登记号" }],
  }
});

const formRef = ref();
const handleSubmit = (data) => {
  formRef.value.validate().then((res) => {
    if(formData.value.traceUrlUnicode == ''){
      return uni.showToast({
        icon: 'none',
        title: "请输入追溯码登记号",
      });
    }
    
    APIS.traceUrl(formData.value.traceUrlUnicode).then((res) => {
      if(res.code === 200){
        if(res.data.traceUrl){
          console.log('res.data.traceUrl: ', res.data.traceUrl)
          uni.navigateTo({
            url: '/pages/webview/index?url=' + encodeURIComponent(res.data.traceUrl)
          });
        }else{
          uni.showToast({
            icon: 'none',
            title: "未查询到追溯码登记号！",
          });
        }
      }
    });
  })
  .catch((err) => {
    console.log("表单错误信息", err);
  });
}

const scanCode = () => {
  console.log('saoyisao1111: ')
  uni.scanCode({
    onlyFromCamera: false, // 是否只从相机扫码，不从相册选择图片
    // scanType: ['qrCode', 'barCode'], // 扫描的类型
    success: function (res) {
      console.log('扫描结果：', res.result);
      console.log('扫描条码类型：', res.scanType);
      console.log('字符集：', res.charSet);
      console.log('路径：', res.path); // 当所扫的码为小程序码时会返回此项

      uni.navigateTo({
        url: '/pages/webview/index?url=' + encodeURIComponent(res.result)
      });
    },
    fail: function (err) {
      console.error('扫码失败：', err);
    },
    complete: function () {
      console.log('扫码操作完成');
    }
  });
};

onMounted(() => {});
</script>

<style lang="scss" scoped>
.container {
  padding: 16upx;

  .flex{
    display: flex;
  }
  .search{
    position: relative;
    top: 9upx;
    margin: 15upx;
  }

  .ft{
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 0;
  }
}
</style>
